package com.wwlwxg.queue;


import lombok.extern.slf4j.Slf4j;

import java.sql.Time;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * 消息队列类，java线程间通信
 */
@Slf4j
public class MessageQueue {

    public static void main(String[] args) {
        MessageQueue queue = new MessageQueue(2);
        for (int i = 0; i < 3; i++) {
            final int id = i;
            new Thread(()->{
                queue.put(new Message(id, "值" + id));
            }, "生产者").start();
        }

        new Thread(()->{

            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message message = queue.take();
            }
        }, "消费者").start();
    }

    // 消息的队列集合
    private LinkedList<Message> list = new LinkedList<Message>();
    private int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    public Message take() {
        synchronized (list) {
            while (list.isEmpty()) {
                try {
                    log.debug("队列为空，消费者线程等待");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 从队列头部获取消息并返回
            Message message = list.removeFirst();
            log.debug("已经消费消息：{}", message);
            list.notifyAll();
            return message;
        }
    }

    public void put(Message message) {
        synchronized (list) {
            // 检查队列是否已经满了
            while (list.size() == capacity) {
                try {
                    log.debug("队列已满，生产者线程等待");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 将消息加入队列尾部
            list.addLast(message);
            log.debug("已经生产消息：{}", message);
            list.notifyAll();
        }
    }

    @Override
    public String toString() {
        return "MessageQueue{" +
                "list=" + list +
                ", capacity=" + capacity +
                '}';
    }
}

class Message {
    private int id;
    private Object data;

    public Message(int id, Object data) {
        this.id = id;
        this.data = data;
    }

    public int getId() {
        return id;
    }

    public Object getData() {
        return data;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", data=" + data +
                '}';
    }
}
